﻿using System;
using System.Collections.Generic;

namespace ExcelMerge;

public static class SpanExtension
{
    public static List<T> ToList<T>(this ReadOnlySpan<T> span)
    {
        var list = new List<T>(span.Length);
        foreach (var item in span)
        {
            list.Add(item);
        }
        return list;
    }
    
    public static int IndexOf<T>(this ReadOnlySpan<T> list, ReadOnlySpan<T> other, int start = 0) where T : IEquatable<T>
    {
        if (other.Length + start > list.Length)
        {
            return -1;
        }
        
        for (int i = start; i + other.Length <= list.Length; i++)
        {
            if (list.Slice(i, other.Length).ElementEquals(other))
            {
                return i;
            }
        }

        return -1;
    }
    
    public static bool ElementEquals<T>(this ReadOnlySpan<T> list, ReadOnlySpan<T> other) where T : IEquatable<T>
    {
        if (list.Length != other.Length)
        {
            return false;
        }

        for (int i = 0; i < list.Length; i++)
        {
            if (!list[i].Equals(other[i]))
            {
                return false;
            }
        }

        return true;
    }
}